package com.scalesoft.artsync.plugins.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Log {

	private enum LOGLEVEL { ERROR, INFO, DEBUG };
	private static String logfile = "artsync.log";
    private static File file = null;

	
	@SuppressWarnings("unchecked")
	public static void info(Object clazz, String message) {
		log(LOGLEVEL.INFO, clazz, message);
	}
	
	@SuppressWarnings("unchecked")
	public static void debug(Object clazz, String message) {
		log(LOGLEVEL.DEBUG, clazz, message);
	}
	
	@SuppressWarnings("unchecked")
	public static void error(Object clazz, String message, Throwable e) {
		log(LOGLEVEL.ERROR, clazz, message, e);
	}
	
	@SuppressWarnings("unchecked")
	public static void i(Object clazz, String message) {
		Log.info(clazz, message);
	}
	
	@SuppressWarnings("unchecked")
	public static void d(Object clazz, String message) {
		Log.debug(clazz, message);
	}
	
	@SuppressWarnings("unchecked")
	public static void e(Object clazz, String message, Throwable e) {
		Log.error(clazz, message, e);
	}

	
//-----------------------------------------------------------------------------------------	
	
	private static void logToFile(String message){
		if (file == null) {
		    file = new File(logfile);
		}
		try {
		    Writer output = new BufferedWriter(new FileWriter(file, true));
			output.write(message);
			output.flush();
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void log(LOGLEVEL loglevel, Object clazz, String message, Throwable e) {
		StringBuilder logMessage = new StringBuilder("");
		logMessage.append(new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(System.currentTimeMillis())));
		logMessage.append(" [");
		logMessage.append(loglevel);
		logMessage.append("] (");
		if (clazz != null && clazz.getClass() != null) {
			logMessage.append(clazz.getClass().getSimpleName());
		}
		logMessage.append(") : ");
		logMessage.append(message);
		if (e != null) {
			logMessage.append("\n");
			logMessage.append(e);
		}
		logMessage.append("\n");
		logToFile(logMessage.toString());
		System.out.print(logMessage.toString());
	}

	@SuppressWarnings("unchecked")
	private static void log(LOGLEVEL loglevel, Object clazz, String message) {
		log(loglevel, clazz, message, null);
	}

	
	

	
}
